<!doctype html>
<html>
<head>

  <title>observeNodes-repeat</title>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <script src="../../../webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="../../polymer.html">

<body>
  
  <script>
    Polymer({
      is: 'x-observes-nodes',
      
      properties: {
        children: {
          type: Array,
          readOnly: true,
          value: function() {
            return [];
          }
        }
      },
      
      _updateChildren: function(info) {
        console.log('Updating children!', info);
        var children = Polymer.dom(this).queryDistributedElements('div');
        this._setChildren(children);
      },
      
      attached: function() {
        Polymer.dom(this).observeNodes(function(info) {
          this._updateChildren(info);
        }.bind(this));
      }
    });

    function randomObject() {
      return {
        name: 'foo'
      };
    }

    function randomArray(size) {
      var array = [];
      for (var i = 0; i < size; ++i) {
        array.push(randomObject());
      }
      return array;
    }

    function numberOfDivs() {
      return Polymer.dom(document).querySelectorAll('div').length;
    }

    function assertDivs(number) {
      console.log('Do we have (' + number + ') divs?', number === numberOfDivs(), 'Actual: ' + numberOfDivs());
    }

    function assertChildren() {
      var observesNodes = Polymer.dom(document).querySelector('x-observes-nodes');
      console.log('Same number of children as divs?', observesNodes.children.length === numberOfDivs(), 'Actual: ' + observesNodes.children.length);
    }



    window.addEventListener('load', function() {
      var dom = document.querySelector('#x-dom');
      
      console.log('Starting tests..');
      
      dom.set('items', randomArray(3));
      
      
      Polymer.Base.async(function() {
      
        assertDivs(3);
        assertChildren();

        dom.set('items', randomArray(6));
        
        Polymer.Base.async(function() {
          assertDivs(6);
          assertChildren();
          
          dom.set('items', randomArray(4));
          
          Polymer.Base.async(function() {
            assertDivs(4);
            assertChildren();
            
            console.log('Tests done!');
          }, 10);
        }, 10);
      }, 10);
    });
  </script>
  
  <template id="x-dom" is="dom-bind">
    <x-observes-nodes><template is="dom-repeat" items="[[items]]"><div>{{item.name}}</div></template></x-observes-nodes>
  </template>
  
</body>
</html>
